package user

import (
	model "gitee.com/enjoy_5/user-rpc/internal/model"
	pb "gitee.com/enjoy_5/user-rpc/proto/user"
	"strconv"
)

// 用户添加
func UserSave(req *pb.SaveUserRequest) (resp *pb.SaveUserResponse, err error) {
	u := model.User{
		UserName: req.UserData.UserName,
		Phone:    req.UserData.Phone,
		Img:      req.UserData.Img,
		Pwd:      req.UserData.Pwd,
	}
	err = u.UserSave()
	if err != nil {
		return nil, err
	}
	data := &pb.SaveUserResponse{}
	data.AddStatus = true
	return data, nil

}

// 用户修改
func UserUpdate(req *pb.UpdUserRequest) (resp *pb.UpdUserResponse, err error) {
	id, _ := strconv.ParseUint(req.UserData.Id, 10, 64)
	u := model.User{}
	u.ID = uint(id)
	// 定义一个映射存储修改的字段
	data := make(map[string]any)
	if req.UserData.UserName != "" {
		data["user_name"] = req.UserData.UserName
	}
	if req.UserData.Phone != "" {
		data["phone"] = req.UserData.Phone
	}
	if req.UserData.Pwd != "" {
		data["pwd"] = req.UserData.Pwd
	}
	if req.UserData.Img != "" {
		data["img"] = req.UserData.Img
	}
	if req.UserData.Status != 0 {
		data["status"] = req.UserData.Status
	}
	if req.UserData.Birthday != 0 {
		data["birthday"] = req.UserData.Birthday
	}
	if req.UserData.Sex != 0 {
		data["sex"] = req.UserData.Sex
	}
	err = u.UserUpdate(data)
	if err != nil {
		return nil, err
	}
	resdata := &pb.UpdUserResponse{}
	resdata.UpdStatus = true
	return resdata, nil

}

// // 查询单个用户
func UserFind(req *pb.UserFirstRequest) (resp *pb.UserFirstResponse, err error) {
	u := model.User{}
	where := make(map[string]any)
	if req.UserName != "" {
		where["user_name"] = req.UserName
	}
	if req.Phone != "" {
		where["phone"] = req.Phone
	}
	if req.Id != "" {
		where["id"] = req.Id
	}
	userData, err := u.Userfind(where)
	if err != nil {
		return nil, err
	}
	data := &pb.UserInfo{
		Id:       strconv.Itoa(int(userData.ID)),
		UserName: userData.UserName,
		Phone:    userData.Phone,
		Img:      userData.Img,
		Pwd:      userData.Pwd,
		Status:   userData.Status,
		Sex:      int64(userData.Sex),
		Birthday: int64(userData.Birthday),
	}
	e := &pb.UserFirstResponse{UserFirst: data}
	return e, nil
}

// 根据用户id查询多条用户
func UserList(req *pb.UserListRequest) (resp *pb.UserListResponse, err error) {
	u := model.User{}
	userData, err := u.UserList(req.Userid)
	if err != nil {
		return nil, err
	}

	var userList []*pb.UserInfo

	for _, val := range userData {
		userInfo := &pb.UserInfo{
			Id:       strconv.Itoa(int(val.ID)),
			UserName: val.UserName,
			Phone:    val.Phone,
			Img:      val.Img,
			Pwd:      val.Pwd,
			Status:   val.Status,
			Sex:      int64(val.Sex),
			Birthday: int64(val.Birthday),
		}
		userList = append(userList, userInfo)
	}
	return &pb.UserListResponse{UserData: userList}, nil
}
